<template>
  <div class="main">
      <div class="city-title">
          <div class="hot-city">热门城市</div>
          <div class="hot-city-list">
              <div class="hot-item" v-for="item in hotCity" :key="item.cityId" @click="changeCity(item)">{{item.name}}</div>
          </div>
      </div>
      <van-index-bar :index-list="indexList">
        <template v-for="item in datalist">
            <van-index-anchor :index="item.charCode" :key="item.charCode">{{item.charCode}}</van-index-anchor>
            <van-cell @click="changeCity(val)" v-for="val in item.list" :key="val.cityId" :title="val.name" />
        </template>
      </van-index-bar>
  </div>
</template>

<script>
import Vue from 'vue'
import { IndexBar, IndexAnchor, Cell } from 'vant'
import url from '../config/url'

Vue.use(IndexBar)
Vue.use(IndexAnchor)
Vue.use(Cell)
export default {
  data () {
    return {
      hotCity: [],
      indexList: [],
      datalist: []
    }
  },
  created () {
    this.$store.commit('common/setIsShowTabBar', false)
    this.$http.get(url.getCitiesInfo).then(res => {
    //   console.log(res)
      const cities = res.data.data.cities
      console.log(cities)
      this.hotCity = cities.filter(item => item.isHot === 1)
      const chars = []
      for (let i = 65; i < 91; i++) {
        chars.push(String.fromCharCode(i))
      }
      chars.forEach(el => {
        let temp = []
        temp = cities.filter(item => item.pinyin.slice(0, 1).toUpperCase() === el)
        if (temp.length > 0) {
          this.datalist.push({
            charCode: el,
            list: temp
          })
          this.indexList.push(el)
        }
        // console.log(this.datalist)
      })
    })
  },
  beforeDestroy () {
    this.$store.commit('common/setIsShowTabBar', true)
  },
  methods: {
    changeCity (item) {
      console.log(item)
      localStorage.setItem('cityId', item.cityId)
      localStorage.setItem('cityName', item.name)
      const goto = this.$route.query.goto ? decodeURI(this.$route.query.goto) : '/'
      this.$router.replace(goto)
    }
  }
}
</script>

<style lang='scss' scoped>
*{box-sizing: border-box;}
.main{
    .city-title{
        padding: 15px 15px 0 15px;
        .hot-city{
            font-size: 13px;
            color: #797d82;
            margin-bottom: 10px;
        }
        .hot-city-list{
            display: flex;
            flex-wrap: wrap;
            justify-content: space-between;
            .hot-item{
                width: 30%;
                padding: 0 8px;
                margin-bottom: 15px;
                font-size: 14px;
                border-radius: 3px;
                height: 30px;
                line-height: 30px;
                color: #191a1b;
                background-color: #f4f4f4;
                text-align: center;
            }
        }
    }
}
</style>
